package com.wgb.movie.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wgb.movie.common.ErrorCode;
import com.wgb.movie.constant.CommonConstant;
import com.wgb.movie.exception.ThrowUtils;
import com.wgb.movie.mapper.MovieEvaluationMapper;
import com.wgb.movie.model.dto.movieEvaluation.MovieEvaluationQueryRequest;
import com.wgb.movie.model.entity.MovieEvaluation;
import com.wgb.movie.model.entity.User;
import com.wgb.movie.model.vo.MovieEvaluationVO;
import com.wgb.movie.model.vo.UserVO;
import com.wgb.movie.service.MovieEvaluationService;
import com.wgb.movie.service.UserService;
import com.wgb.movie.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 评价服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class MovieEvaluationServiceImpl extends ServiceImpl<MovieEvaluationMapper, MovieEvaluation> implements MovieEvaluationService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param movieEvaluation
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validMovieEvaluation(MovieEvaluation movieEvaluation, boolean add) {
        ThrowUtils.throwIf(movieEvaluation == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值

        Long movieId = movieEvaluation.getMovieId();
        Long userId = movieEvaluation.getUserId();
        Integer rating = movieEvaluation.getRating();


        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(movieId==null||movieId<=0, ErrorCode.PARAMS_ERROR, "电影id不合法");
            ThrowUtils.throwIf(userId==null||userId<=0, ErrorCode.PARAMS_ERROR, "用户id不合法");
            ThrowUtils.throwIf(rating==null||rating<=0, ErrorCode.PARAMS_ERROR, "评分不合法");
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则

    }

    /**
     * 获取查询条件
     *
     * @param movieEvaluationQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<MovieEvaluation> getQueryWrapper(MovieEvaluationQueryRequest movieEvaluationQueryRequest) {
        QueryWrapper<MovieEvaluation> queryWrapper = new QueryWrapper<>();
        if (movieEvaluationQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = movieEvaluationQueryRequest.getId();

        Long movieId = movieEvaluationQueryRequest.getMovieId();
        Long userId = movieEvaluationQueryRequest.getUserId();

        String sortField = movieEvaluationQueryRequest.getSortField();
        String sortOrder = movieEvaluationQueryRequest.getSortOrder();

        // todo 补充需要的查询条件
        // 从多字段中搜索

        // 模糊查询

        // JSON 数组查询

        // 精确查询

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(movieId), "movieId", movieId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取评价封装
     *
     * @param movieEvaluation
     * @param request
     * @return
     */
    @Override
    public MovieEvaluationVO getMovieEvaluationVO(MovieEvaluation movieEvaluation, HttpServletRequest request) {
        // 对象转封装类
        MovieEvaluationVO movieEvaluationVO = MovieEvaluationVO.objToVo(movieEvaluation);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = movieEvaluation.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        movieEvaluationVO.setUser(userVO);
        // 2. 已登录，获取用户点赞、收藏状态

        // endregion

        return movieEvaluationVO;
    }

    /**
     * 分页获取评价封装
     *
     * @param movieEvaluationPage
     * @param request
     * @return
     */
    @Override
    public Page<MovieEvaluationVO> getMovieEvaluationVOPage(Page<MovieEvaluation> movieEvaluationPage, HttpServletRequest request) {
        List<MovieEvaluation> movieEvaluationList = movieEvaluationPage.getRecords();
        Page<MovieEvaluationVO> movieEvaluationVOPage = new Page<>(movieEvaluationPage.getCurrent(), movieEvaluationPage.getSize(), movieEvaluationPage.getTotal());
        if (CollUtil.isEmpty(movieEvaluationList)) {
            return movieEvaluationVOPage;
        }
        // 对象列表 => 封装对象列表
        List<MovieEvaluationVO> movieEvaluationVOList = movieEvaluationList.stream().map(movieEvaluation -> {
            return MovieEvaluationVO.objToVo(movieEvaluation);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = movieEvaluationList.stream().map(MovieEvaluation::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态

        // 填充信息
        movieEvaluationVOList.forEach(movieEvaluationVO -> {
            Long userId = movieEvaluationVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            movieEvaluationVO.setUser(userService.getUserVO(user));

        });
        // endregion

        movieEvaluationVOPage.setRecords(movieEvaluationVOList);
        return movieEvaluationVOPage;
    }

}
